--- 19,重庆川仪电磁流量计 modbus 9600,N,8,1
module(..., package.seeall)
local logtag = "CQCY_DC"
local cid, uid,addr= 3, 3 ,1   -- 默认用3通道
local dtu, udtu = {}, {} -- 配置文件
local meter_ins, meter_val

function setDtu(dtup, udtup)
    dtu, udtu = dtup, udtup
    addr = udtu.addr and tonumber(udtu.addr) or 1
    if udtu and tonumber(udtu.dtype) == 19 then sys.taskInit(init) end
end

local function process(data, status)
    if #data > 8 then
        local temp = data:sub(6, 7) .. data:sub(4, 5)
        if status == 2 then
            _1, meter_ins = pack.unpack(temp, ">f")
            meter_ins = string.format("%.2f", meter_ins)
            lcd.LCD_DATA[3] = '流量:' .. (meter_ins or 0)
        elseif status == 1 then
            _2, meter_val = pack.unpack(temp, ">I")
            lcd.LCD_DATA[3] = '累计:' .. (meter_val or 0)
        end
        if meter_val and meter_ins then
            usrdata.update({meter_val, meter_ins})
        end
    end
end
function init()
    power.openBoost()
    sys.wait(200)
    local status = 1
    while true do
        if status == 1 then
            status = 2
            tools.modbus_send(3, addr, 3, 4, 2)
        elseif status == 2 then
            status = 1
            tools.modbus_send(3, addr, 3, 12, 2)
        end
        log.warn(logtag, "间隔10秒等待串口数据,UART" .. uid)
        -- 等待串口回复
        local result, d = sys.waitUntil('UART_READ_DONE_NEXT_' .. uid, 5000)
        if result then
            if (d) then
                process(d, status)
            end
            sys.wait(5 * 1000) -- 5秒切换读取
        else
            lcd.LCD_DATA[3] = "川仪READ TIMEOUT"
        end
    end
end
